package composite

import (
	"fmt"
	"strings"
)

type Department struct {
	List   map[string]*Department
	Parent *Department
	Name   string
	Id     string
	Depth  int
}

// 批量添加子节点
func (d *Department) Add(departments ...*Department) {
	for _, department := range departments {
		department.AddTo(d)
	}
}

// 添加到对应的父节点
func (d *Department) AddTo(parent *Department) {
	d.Parent = parent
	parent.add(d)
}

// 添加子节点
func (d *Department) add(department *Department) {
	if d.List == nil {
		d.List = make(map[string]*Department)
	}
	d.List[department.Id] = department
}

// 查找子节点
func (d *Department) Find(id string) (department *Department) {
	department, ok := d.List[id]
	if !ok {
		for _, de := range d.List {
			department = de.Find(id)
			if nil != department {
				return
			}
		}
		return
	}
	return
}

// 移除子节点
func (d *Department) Remove(id string) (department *Department) {
	department, ok := d.List[id]
	if !ok {
		for _, de := range d.List {
			department = de.Remove(id)
			if nil != department {
				return
			}
		}
		return
	}
	delete(d.List, id)
	return
}

// 遍历
func (d *Department) ReadList() {
	fmt.Printf("%s Node :%s(%s)\n", strings.Repeat("-", d.Depth - 1), d.Id, d.Name)
	for _, de := range d.List {
		de.ReadList()
	}
}
